package com.projectexercise.book.controller;

import com.projectexercise.book.model.UserInfo;
import com.projectexercise.book.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Date;

@RequestMapping("/user")
@RestController
public class UserController {
    @Autowired
    public UserService userService;
    private static final String SESSION_KEY = "KAPTCHA_SESSION_KEY";
    private static final String SESSION_DATE = "KAPTCHA_SESSION_DATE";
    private final static long VALID_MILLIS_TIME = 60 * 1000;
    @RequestMapping("/login")
    public Boolean login(String username, String password, String captcha, HttpSession session){
        if(!StringUtils.hasLength(username) || !StringUtils.hasLength(password)
                || !StringUtils.hasLength(captcha)){
            return false;
        }
//        if("admin".equals(username) && "admin".equals(password)){
//            session.setAttribute("username",username);
//            return true;
//        }
        UserInfo userInfo = userService.getUserInfoByName(username);
        if(userInfo == null){
            return false;
        }
        if(!password.equals(userInfo.getPassword())){
            return false;
        }
        String string = (String) session.getAttribute(SESSION_KEY);
        Date date = (Date) session.getAttribute(SESSION_DATE);
        if(!captcha.equalsIgnoreCase(string)){
            return false;
        } else if (!(System.currentTimeMillis() - date.getTime() < VALID_MILLIS_TIME)){
            return false;
        }
        session.setAttribute("user_session",userInfo);
        return true;
    }
}
